/**
 * 
 */
var dataId = 0;
var maxpage = -1;
var page = 1;
var stopStatusInterval = "";
var stopFormInterval = "";

$(function(){ 
	getUserModul();
	setUnityInterval('getUserModul()',120000);
});

window.onresize = function(){
	$("#body").css("z-index",1);
}

//查询
function check(){
	$("#shade").show();
	$("#statusform").show();
}

//隐藏窗口
function hide(){
	cleanAll();
	$("#shade").hide();
	$("#statusform").hide();
}

//清除所有窗口数据
function cleanAll() {
	dataId = 0;
	$("#status_title").html("");
	$("#container6").html("");
	$(".form-page-nav").removeClass("active");
	clearInterval(stopStatusInterval);
	clearInterval(stopFormInterval);
}

//页面数据刷新
function setUnityInterval(name,time){
	return setInterval(name,time);//周期20秒
}

//检测登录状态
function checkUserLogin(){
	$.post("CheckLogin.action",
		function (data){
			if (data != "true") location.href='./login.jsp';
		}
	);
}

//获取用户信息
function getUserModul(){
	checkUserLogin();
	$.post("GetWarningNumber.action",
		function (data){
			var result = $.parseJSON(data);
			console.log(result);
			var areaList = result[0];
			var typeList = result[1];
			var deviceList = result[2];
			console.log(areaList);
			console.log(typeList);
			console.log(deviceList);
			if (areaList.length > 0) {
				var areaBrowsers = [];
				$.each(areaList,function(i,d){
					areaBrowsers.push({name:d.name,data:[d.num]});
				})
				getColumnChart(areaBrowsers);
			}
			 
			if (typeList.length > 0) {
				var typeBrowsers = [];
				typeBrowsers.push({name:"漏电报警",y:typeList[0].warning1});
				typeBrowsers.push({name:"故障电弧报警",y:typeList[0].warning2});
				getPieChart(typeBrowsers);
			}
			 
			if (deviceList.length > 0) {
				var deviceBrowsers = [];
				$.each(deviceList,function(i,d){
					if (d.PositionX > 0) deviceBrowsers.push({name:d.address,position:[d.PositionX,d.PositionY]});
				})
				console.log(deviceBrowsers);
				getMap(deviceBrowsers);
			}
		}
	);
}

//获取表格start
function getPageData(page,type=0) {
	if (maxpage == 0) {
		maxpage++;
	}else if (maxpage > 0 && page > maxpage) {
		if (type == 1) {
			alert("请输入有效页数");
		}else{
			page = maxpage;
			//alert("没有下一页");
		}
		return;
	}else if (page <= 0) {
		page = 1;
		//alert("没有上一页！");
		return;
	}

	var html = "";
	var warningType;
	var time = new Date( +new Date() + 8 * 3600 * 1000 ).toJSON().substr(0,19).replace("T"," ");
	size = 7;
	$("#form_table_tr2").html("");
	$.post("GetWarningData.action",
	{
		startdate: $("#fault_datetime_start").val(),
		stopdate: $("#fault_datetime_end").val(),
		pagecount: page,
	},function(data){
		var result = $.parseJSON(data);
		console.log(result);
		var total = result[0].total;
		var startnum = (page - 1) * size + 1;
		var endnum = page * size;
		if (endnum > total) {
			endnum = total;
		}
		if (total % size === 0) {
			maxpage = total / size;
		}else{
			maxpage = parseInt(total / size) + 1;
		}
		
		$.each(result,function(i,d){
			if (i > 0) {
				warningType = d.type == 1 ? "漏电报警" : "故障电弧报警";
				html += '<tr class="form-table-tr">';
				html += '<td>' + d.SeriesNumber + '</td>';
				html += '<td>' + d.area + '</td>';
				html += '<td>' + d.address + '</td>';
				html += '<td>' + warningType + '</td>';
				html += '<td>' + d.Datetime + '</td>';
				html += '</tr>';
			}
		});
		$("#form_page_current_fault").html(page);
		$("#form_page_total_fault").html(maxpage);
		$("#form_table_tr2").html(html);
	});
}

//上一页
function lastPage(){
	if (page == 1) {
		//alert("没有上一页");
		return;
	}
	page--;
	getPageData(page);
}

//下一页
function nextPage(){
	if (maxpage == page) {
		//alert("没有下一页");
		return;
	}
	page++;
	getPageData(page);
}

//跳转指定页面
function jumpPage(){
	id = "#form_page_jump_fault";
	if ($(id).val() > 0 && $(id).val() <= maxpage) {
		page = $(id).val();
		getPageData(page,1);
	}else{
		alert("请输入有效页数");
		return;
	}
}
$("#form_page_jump_fault").keypress(function (e) {
	if (e.which == 13) {
		jumpPage();
	}
});
//获取表格end

function getMap(mapData){
    //初始化地图对象，加载地图
    var map = new AMap.Map("container", {
		resizeEnable: true,
		zoom:11,//级别
	});
	var icon = new AMap.Icon({
		size: new AMap.Size(20, 30),    // 图标尺寸
		image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',  // Icon的图像
		imageSize: new AMap.Size(20, 30)   // 根据所设置的大小拉伸或压缩图片
	});
    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -5)});
    for (var i = 0, marker; i < mapData.length; i++) {
        var marker = new AMap.Marker({
            position: mapData[i].position,
			icon: icon,
            map: map
        });
        marker.content = mapData[i].name;
        marker.on('click', markerClick);
    }
    function markerClick(e) {
        infoWindow.setContent(e.target.content);
        infoWindow.open(map, e.target.getPosition());
    }
    map.setFitView();
}

function getPieChart(pieData) {
	Highcharts.chart('container1', {
		chart: {
			type: 'pie',
			backgroundColor: 'rgba(0,0,0,0)',
			options3d: {
				enabled: true,
				alpha: 45,
				beta: 0
			}
		},
		title: {
			text: '',
			style: {
				display: 'none'
			}
		},
		tooltip: {
			pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b><br/>报警数量: <b>{point.y}</b>'
		},
		legend: {
		　　layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            borderWidth: 0,
			itemStyle: {
				color: '#fff',
				'fontSize': '12px',
				'fontWeight': 'unset',
			}
		},
		plotOptions: {
			pie: {
				allowPointSelect: true,
				cursor: 'pointer',
				depth: 15,
				showInLegend: true,
				dataLabels: {
					enabled: false,
					format: '{point.name}',
					style: {
						color: '#fff',
					}
				},
			}
		},
		colors: ['#6CF', '#FFEB3B', '#FF9800', '#4CAF50', '#ffc107', '#faebcc', '#ff5722'],
		series: [{
			type: 'pie',
			name: '报警类型占比',
			data: pieData
		}]
	});
}

function getColumnChart(columnData) {
	Highcharts.chart('container2', {
		chart: {
			type: 'column',
			backgroundColor: 'rgba(0,0,0,0)',
			style: {"color":"#999"},
			zoomType: 'x'
		},
		title: {
			text: '',
			style: {
				display: 'none'
			}
		},
		xAxis: {
			labels: {
				enabled: false
			}
		},
		yAxis: {
			title: {
				text: '',
				style: {
					display: 'none'
				}
			},
			labels: {
				style: {"color":"#fff"}
			}
		},
		legend: {
		　　layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            borderWidth: 0,
			itemStyle: {
				color: '#fff',
				'fontSize': '12px',
				'fontWeight': 'unset',
			}
		},
		plotOptions: {
			series: {
				borderWidth: 0,
				dataLabels: {
					enabled: true,
					format: '{point.y}',
					style: {
						color: '#fff',
						'fontSize': '12px',
						'fontWeight': 'unset',
					}
				}
			}
		},
		tooltip: {
			headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
			pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b> 故障点<br/>'
		},
		colors: ['#6CF', '#FFEB3B', '#FF9800', '#4CAF50', '#ffc107', '#faebcc', '#ff5722'],
		series: columnData,
	});
}